import crypto from 'node:crypto'
import { Buffer } from 'node:buffer'

export function generateKey(key) {
    return crypto.createHash('sha256').update(key).digest()
}

export function encrypt(text, key) {
    const iv = crypto.randomBytes(16)
    const cipher = crypto.createCipheriv('aes-256-cbc', key, iv)
    const encrypted = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()])
    return Buffer.concat([iv, encrypted]).toString('base64')
}

export function decrypt(encryptedText, key) {
    const data = Buffer.from(encryptedText, 'base64')
    const iv = data.subarray(0, 16)
    const ciphertext = data.subarray(16)
    const decipher = crypto.createDecipheriv('aes-256-cbc', key, iv)
    const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()])
    return decrypted.toString('utf8')
}

export function md5(text) {
    const sha256 = crypto.createHash('sha256')
    return sha256.update(text).digest('hex')
}
